package com.yvon.maple.service.auth.authentication.email;

import com.yvon.maple.service.auth.enums.CodeTypeEnum;
import com.yvon.maple.service.auth.service.SecurityUserService;
import com.yvon.maple.service.auth.valicode.validate.code.processor.CodeValidator;
import com.yvon.maple.service.auth.vo.ValidateVo;
import lombok.Data;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 邮箱身份验证提供者
 *
 * @author : Yvon
 * @since : 2021-08-25
 */
@Data
public class EmailAuthenticationProvider implements AuthenticationProvider {


	private final SecurityUserService securityUserService;

	private final CodeValidator codeValidator;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		EmailAuthenticationToken authenticationToken = (EmailAuthenticationToken) authentication;
		ValidateVo smsCode = ValidateVo.builder().code((String) authenticationToken.getCredentials()).key((String) authenticationToken.getPrincipal()).codeType(CodeTypeEnum.EMAIL).build();
		if (!codeValidator.validate(smsCode)) {
			throw new BadCredentialsException("邮箱验证码错误");
		}
		UserDetails user = securityUserService.loadUserByEmail((String) authenticationToken.getPrincipal());
		EmailAuthenticationToken authenticationResult = new EmailAuthenticationToken(user, user.getAuthorities());
		authenticationResult.setDetails(authenticationToken.getDetails());
		return authenticationResult;
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return EmailAuthenticationToken.class.isAssignableFrom(authentication);
	}


}